<?php

namespace App\Console\Commands;

use App\Models\ChallengeGame;
use Carbon\Carbon;
use Illuminate\Console\Command;

class UpdateVirtualMatch extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'update:virtual-match';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '更新虚拟比赛';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $today = Carbon::today();
        $todayStr = Carbon::parse($today)->toDateString();

        $latestGameDatetime = ChallengeGame::where([['is_true', 0]])->latest('game_datetime')->value('game_datetime');
        $latestGameDate = Carbon::parse($latestGameDatetime)->toDateString();

        if ($latestGameDate < $todayStr) {
            $oldestGameDatetime = ChallengeGame::where([['is_true', 0]])->oldest('game_datetime')->value('game_datetime');
            $limitDate = Carbon::parse($oldestGameDatetime)->toDateString();
            $limitDatetime = $limitDate . ' 23:59:59';

            //计算日期差
            $diffDays = $today->diffInDays(Carbon::parse($limitDate));

            $exp = 'date_add(game_datetime, interval ' . $diffDays . ' day)';

            ChallengeGame::where([['is_true', 0], ['game_datetime', '<=', $limitDatetime]])
                ->update(['game_datetime' => \DB::raw($exp), 'view' => 0]);

        }

        $this->info('执行完成');

    }
}
